<template>
  <div class="admin-dashboard">
    <!-- 控制台概览 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="8">
        <el-card class="dashboard-card">
          <div class="card-icon" style="background-color: #409EFF">
            <i class="el-icon-user"></i>
          </div>
          <div class="card-content">
            <div class="card-title">社团总数</div>
            <div class="card-value">{{ stats.clubCount }}</div>
            <div class="card-footer">
              <span>系统所有社团</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="dashboard-card">
          <div class="card-icon" style="background-color: #67C23A">
            <i class="el-icon-data-line"></i>
          </div>
          <div class="card-content">
            <div class="card-title">活动数量</div>
            <div class="card-value">{{ stats.activityCount }}</div>
            <div class="card-footer">
              <span>系统所有活动</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="dashboard-card">
          <div class="card-icon" style="background-color: #E6A23C">
            <i class="el-icon-bell"></i>
          </div>
          <div class="card-content">
            <div class="card-title">待审核申请</div>
            <div class="card-value">{{ stats.pendingCount }}</div>
            <div class="card-footer">
              <span>需要处理</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动参与人数图表 -->
    <el-row class="content-cards">
      <el-col :span="24">
        <el-card class="equal-height-card">
          <div slot="header">
            <span>活动参与人数统计</span>
            <div style="float: right;">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                @change="handleDateRangeChange">
              </el-date-picker>
            </div>
          </div>
          <div class="chart-container" v-loading="chartLoading">
            <div ref="activityChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待审核社团 - 调整为占据整行 -->
    <el-row class="content-cards">
      <el-col :span="24">
        <el-card class="equal-height-card">
          <div slot="header">
            <span>待审核社团</span>
            <el-button style="float: right; padding: 3px 0" type="text">查看全部</el-button>
          </div>
          <el-table :data="pendingClubs.slice(0, 4)" style="width: 100%" height="250" v-loading="pendingClubsLoading">
            <el-table-column prop="title" label="社团名称"></el-table-column>
            <el-table-column prop="category" label="类别" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.category">
                <el-tag 
                  v-for="(tag, index) in scope.row.category.split(',')" 
                  :key="index"
                  :type="getTagType(tag.trim())"
                  style="margin-right: 5px; margin-bottom: 5px;">
                  {{ tag.trim() }}
                </el-tag>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
            <el-table-column prop="createTime" label="申请时间" align="center" />
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="openClubDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 对话框组件保持不变 -->
    <el-dialog title="社团详情" :visible.sync="clubDetailVisible" width="70%">
      <!-- 对话框内容保持不变 -->
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";
import * as echarts from 'echarts';

export default {
  name: 'AdminDashboard',
  data() {
    return {
      activeMenu: '/admin/dashboard',
      currentPage: '控制台概览',
      loading: false,
      adminInfo: JSON.parse(localStorage.getItem('adminInfo') || '{}'),
      
      // 统计数据
      stats: {
        clubCount: 0,
        activityCount: 0,
        pendingCount: 0
      },
      
      pendingClubs: [],
      pendingActivities: [],
      pendingClubsLoading: false,
      
      clubDetailVisible: false,
      currentClub: null,
      reviewComment: '',
      clubActivities: [],
      clubMembers: [],
      attachments: [],
      
      // 图表相关
      chartLoading: false,
      activityChart: null,
      activityData: [],
      dateRange: [
        this.getDefaultStartDate(),
        this.getDefaultEndDate()
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.fetchStats();
    this.getPendingClubs();
    this.getPendingActivities();
  },
  mounted() {
    this.fetchActivityData();
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.activityChart) {
      this.activityChart.dispose();
      this.activityChart = null;
    }
  },
  methods: {
    // 获取统计数据
    async fetchStats() {
      try {
        // 获取社团总数
        const clubCountRes = await httpInstance.get('/api/club/num');
        if (clubCountRes.code === 200) {
          this.stats.clubCount = clubCountRes.data || 0;
        }
        
        // 获取活动总数
        const activityCountRes = await httpInstance.get('/api/activity/num');
        if (activityCountRes.code === 200) {
          this.stats.activityCount = activityCountRes.data || 0;
        }
        
        // 待审核申请数量需要计算社团申请和活动申请的总和
        await this.calculatePendingCount();
        
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      }
    },
    
    // 计算待审核申请数量
    async calculatePendingCount() {
      try {
        // 获取待审核社团
        const pendingClubsRes = await httpInstance.post('/api/club/approveList');
        const pendingClubs = pendingClubsRes.code === 200 ? pendingClubsRes.data || [] : [];
        
        // 获取待审核活动
        const pendingActivitiesRes = await httpInstance.post('/api/activity/approveList');
        const pendingActivities = pendingActivitiesRes.code === 200 ? pendingActivitiesRes.data || [] : [];
        
        // 计算总数
        this.stats.pendingCount = pendingClubs.length + pendingActivities.length;
        
        // 同时存储待审核列表，避免重复请求
        this.pendingClubs = pendingClubs;
        this.pendingActivities = pendingActivities;
        
      } catch (error) {
        console.error('计算待审核申请数量失败:', error);
        this.stats.pendingCount = 0;
      }
    },
    
    // 获取默认开始日期（当前日期前15天）
    getDefaultStartDate() {
      const date = new Date();
      date.setDate(date.getDate() - 14);
      return this.formatDateToString(date);
    },
    
    // 获取默认结束日期（当前日期）
    getDefaultEndDate() {
      return this.formatDateToString(new Date());
    },
    
    // 格式化日期为字符串 YYYY-MM-DD
    formatDateToString(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 日期范围改变时触发
    handleDateRangeChange() {
      this.fetchActivityData();
    },
    
    // 获取活动参与数据
    async fetchActivityData() {
      if (!this.dateRange || !this.dateRange[0] || !this.dateRange[1]) {
        return;
      }
      
      this.chartLoading = true;
      
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        };
        
        const res = await httpInstance.post('/api/statistics/activity-participants', params);
        
        if (res.code === 200) {
          this.activityData = res.data || [];
          this.initActivityChart();
        } else {
          this.$message.error(res.msg || '获取活动参与数据失败');
        }
      } catch (error) {
        console.error('获取活动参与数据失败:', error);
        this.$message.error('获取活动参与数据失败，请稍后重试');
      } finally {
        this.chartLoading = false;
      }
    },
    
    // 初始化活动参与图表
    initActivityChart() {
      const chartDom = this.$refs.activityChart;
      
      // 如果已有图表实例，先销毁
      if (this.activityChart) {
        this.activityChart.dispose();
      }
      
      // 创建新的图表实例
      this.activityChart = echarts.init(chartDom);
      
      // 准备数据
      const dates = this.activityData.map(item => item.date);
      const counts = this.activityData.map(item => item.count);
      
      // 图表配置
      const option = {
        title: {
          text: '活动参与人数趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br />{a}: {c}人'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45 // 当日期多时，旋转标签防止重叠
          }
        },
        yAxis: {
          type: 'value',
          name: '参与人数',
          minInterval: 1 // 确保y轴以整数显示
        },
        series: [
          {
            name: '参与人数',
            type: 'line',
            data: counts,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.7)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.1)'
                }
              ])
            },
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            }
          }
        ]
      };
      
      // 设置图表选项
      this.activityChart.setOption(option);
      
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        this.activityChart.resize();
      });
    },
    
    // 获取待审核社团列表
    async getPendingClubs() {
      this.pendingClubsLoading = true;
      try {
        const response = await httpInstance.post('/api/club/approveList');
        
        if (response && response.code === 200) {
          this.pendingClubs = response.data || [];
          console.log("获取到的待审核社团:", this.pendingClubs);
        } else {
          this.$message.error(response?.msg || '获取待审核社团列表失败');
          this.pendingClubs = [];
        }
      } catch (error) {
        console.error('获取待审核社团列表失败:', error);
        this.$message.error('获取待审核社团列表失败，请稍后重试');
        this.pendingClubs = [];
      } finally {
        this.pendingClubsLoading = false;
      }
    },
    
    // 获取待审核活动列表
    async getPendingActivities() {
        try {
        const response = await httpInstance.post('/api/activity/approveList');
          
          if (response && response.code === 200) {
          this.pendingActivities = response.data || [];
          } else {
          this.pendingActivities = [];
        }
        } catch (error) {
        console.error('获取待审核活动列表失败:', error);
        this.pendingActivities = [];
          }
    },
    
    // 打开社团详情对话框
    openClubDetail(club) {
      this.currentClub = club;
      this.reviewComment = '';
      this.clubDetailVisible = true;
    },
    
    // 获取标签类型
    getTagType(category) {
        category = category.trim();
        const typeMap = {
          '学术科技': 'primary',
          '文化艺术': 'success',
          '体育运动': 'warning',
          '社会实践': 'danger',
          '志愿公益': 'info'
        };
        
        // 如果找不到精确匹配，尝试部分匹配
        if (typeMap[category]) {
          return typeMap[category];
        }
        
        // 部分匹配
        if (category.includes('学术') || category.includes('科技')) return 'primary';
        if (category.includes('文化') || category.includes('艺术')) return 'success';
        if (category.includes('体育') || category.includes('运动')) return 'warning';
        if (category.includes('社会') || category.includes('实践')) return 'danger';
        if (category.includes('志愿') || category.includes('公益')) return 'info';
        
        // 默认返回
        return '';
      },
    
    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
      if (!date) return '';
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped>
.content-cards {
      margin-top: 20px;
    }

.equal-height-card {
      height: 100%;
  margin-bottom: 20px;
    }

.chart-container {
  height: 400px;
  position: relative;
    }

/* 其他样式保持不变 */
.admin-dashboard {
  display: flex;
  flex-direction: column;
}

/* 侧边栏样式 */
.sidebar {
  height: 100%;
  background-color: #001529;
  color: white;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #002140;
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.sidebar-menu {
  border-right: none;
}

/* 头部导航样式 */
.el-header {
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-sidebar {
  font-size: 20px;
  margin-right: 20px;
  cursor: pointer;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
}

/* 主内容区样式 */
.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  height: calc(100vh - 60px);
}

/* 卡片样式 */
.dashboard-cards {
  margin-bottom: 20px;
}

.dashboard-card {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.card-icon i {
  font-size: 30px;
  color: white;
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.card-footer {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.trend {
  display: flex;
  align-items: center;
  margin-right: 8px;
}

.trend.up {
  color: #67C23A;
}

.trend.down {
  color: #F56C6C;
}

.period {
  color: #909399;
}

/* 确保容器可以滚动 */
.el-container {
  height: 100vh;
  overflow: hidden;
}

.el-container .el-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
